<?php
namespace app\restaurant\model;

use app\BaseModel;
use app\member\info\PermissionMember;
use app\member\model\Level;
use think\facade\Db;

class Car extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_restaurant_car';


    protected $append = [

        'spe_name',

        'feeding_name'

    ];

    /**
     * @param $value
     * @param $data
     * @功能说明:
     * @author chenniang
     * @DataTime: 2020-10-09 16:54
     */
    public function getFeedingNameAttr($value,$data){

        if(!empty($data['feeding'])){

            $feeding  = explode(',',$data['feeding']);

            $feeding_model  = new Feeding();

            $spe_name = $feeding_model->where('id','IN',$feeding)->column('title');

            return  implode('+',$spe_name);

        }

    }

    /**
     * @param $value
     * @param $data
     * @功能说明:
     * @author chenniang
     * @DataTime: 2020-10-09 16:54
     */
    public function getSpeNameAttr($value,$data){

        if(!empty($data['norml'])){

            $spe_id   = Db::name('longbing_card_restaurant_spe_price')->where(['id'=>$data['norml']])->value('spe_id');

            $pec_id   = !empty($spe_id)?explode('-',$spe_id):[];

            $spe_name = Db::name('longbing_card_restaurant_spe')->where(['status'=>1])->where('id','IN',$pec_id)->column('title');

            return  implode('+',$spe_name);

        }

    }

    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:分类添加
     */
    public function carAdd($data){

        $data['create_time'] = time();

        $data['update_time'] = time();

        $res = $this->insert($data);

        return $res;

    }



    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:分类编辑
     */
    public function carUpdate($dis,$data){

        $data['update_time'] = time();

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function carList($type,$user_id,$uniacid,$store_id){

        //获取购物车信息
        $data = $this->getCarList($user_id,$type,$uniacid,$store_id);
        //计算价格
        $arr  = $this->getCarPrice($data,$user_id,$uniacid,$type);

        return $arr;
    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:
     */
    public function carInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-22 13:57
     * @功能说明:获取所有购物车信息
     */
    public function getCarList($user_id,$type,$uniacid,$store_id){

        $dis[] = ['a.status','=',1];

        $dis[] = ['b.status','=',1];

        $dis[] = ['a.uniacid','=',$uniacid];

        $dis[] = ['a.store_id','=',$store_id];

        $dis[] = ['a.user_id','=',$user_id];

        if($type==0){
            //外卖
            $dis[] = ['b.out_foods','=',1];

        }elseif($type==1){
            //堂食
            $dis[] = ['b.house_foods','=',1];

        }else{
            //自提
            $dis[] = ['b.self_foods','=',1];

        }
        $data = $this->alias('a')
            ->join('longbing_card_restaurant_goods b','a.goods_id = b.id')
            ->join('longbing_card_restaurant_spe_price c','a.norml = c.id AND c.goods_id = b.id')
            ->where($dis)
            ->field(['a.id as car_id','a.norml','b.cate_id','c.weight','b.self_foods','b.out_foods','house_foods','a.id','c.cost_price','b.title','b.cover','a.feeding','b.lunch_fee as lunch_price','a.goods_id','a.num','c.id as spe_id','c.price','c.original_price','c.stock','c.member_price'])
            ->group('a.goods_id,a.norml,a.feeding')
            ->order('a.id desc')
            ->select()
            ->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-22 14:04
     * @功能说明:计算价格
     */
    public function getCarPrice($data,$user_id,$uniacid,$type=0,$coupon_id = 0,$address_id=0,$store_id=0,$user_num = 0){

        $level_model = new Level();
        //查看是否是会员
        $leve = $level_model->getUserLevel($user_id,$uniacid);
        //会员权限
        $member_p = new PermissionMember($uniacid);

        $auth = $member_p->pAuth();

        $leve = $auth==true?$leve:0;

        $feeding_model   = new Feeding();

        $goods_price     = 0;

        $total_lunch_fee = 0;

        $member_price    = 0;

        $total_feeding_fee = 0;

        $true_price = 0;

        $weight     = 0;

        $meal_fee   = 0;

        if(!empty($data)){

            foreach ($data as &$v){

                $feeding_price = 0;
                //加料
                if(!empty($v['feeding'])){

                    $feeding_id = explode(',',$v['feeding']);

                    $v['feeding'] = $feeding_model->where('id','in',$feeding_id)->select();

                    $feeding_price= $feeding_model->where('id','in',$feeding_id)->sum('price');

                }

                $v['lunch_price']   = $type==1?0:$v['lunch_price'];
                //加上加料的钱
                $v['original_price']+= $feeding_price;

                $v['price']        += $feeding_price;
                //加上加料的钱
                $v['member_price'] += $feeding_price;

                $v['feeding_price'] = $feeding_price;
                //总加料价格
                $total_feeding_fee += $feeding_price*$v['num'];
                //商品价格（含加料）
                $goods_price       += $v['price']*$v['num'];
                //会员价
                $member_price      += $v['member_price']*$v['num'];
                //餐盒费
                $total_lunch_fee   += $v['lunch_price']*$v['num'];

                $v['true_price']    = !empty($leve)?$v['member_price']:$v['price'];

                $true_price        += $v['true_price']*$v['num'];
                //总重量
                $weight            += $v['weight']*$v['num'];

            }

        }

        $express_price = 0;
        //外卖才有配送费
        if(!empty($address_id)&&!empty($store_id)&&$type==0){

            $address = Db::name('longbing_card_shop_address')->where(['id'=>$address_id])->find();

            $delivery_model = new Delivery();

            $express_price  = $delivery_model->getFee($store_id,$address);

        }
        //餐位费
        if(!empty($store_id)&&$type==1){

            $store_model = new Store();
            //门店信息 主要看门店的配送方式
            $store = $store_model->storeInfo(['id'=>$store_id]);
            //餐位费 只有堂食才有
            $meal_fee = round($store['meal_fee']*$user_num,2);
        }

        $arr['list'] = $data;

        $arr['coupon_id']           = $coupon_id;
        //餐位费
        $arr['meal_fee']            = $meal_fee;

        $arr['express_price']       = $express_price;
        //主要计算优惠券
        $arr                        = $this->getTruePayPrice($arr);
        //优惠券金额
        $coupon_price               = $arr['discount_price'];
        //优惠券折扣
        $arr['coupon_price']        = round($true_price - $coupon_price,2)>0?$coupon_price:$true_price;
        //商品价格
        $arr['goods_price']         = round($true_price,2);
        //商品原价
        $arr['init_goods_price']    = round($goods_price,2);
        //减去优惠券的价格
        $true_price                 = round($true_price - $coupon_price,2)>0?round($true_price - $coupon_price,2):0;
        //加料总费用
        $arr['total_feeding_price'] = round($total_feeding_fee,2);
        //总的餐盒费
        $arr['total_lunch_price']   = round($total_lunch_fee,2);
        //总原价格价格
        $arr['init_total_price']    = round($goods_price+$total_lunch_fee+$express_price+$meal_fee,2);
        //支付价格
        $arr['total_price']         = round($true_price+$total_lunch_fee+$express_price+$meal_fee,2);
        //是否是会员订单
        $arr['is_member']           = !empty($leve)?1:0;
        //会员商品折扣
        $arr['member_price']        = !empty($leve)?round($goods_price-$member_price,2):0;

        $arr['weight']              = $weight;

        return $arr;

    }


    /**
     * @param $data
     * @功能说明:主要计算优惠券
     * @author chenniang
     * @DataTime: 2020-10-23 13:39
     */
    public function getTruePayPrice($data){

        $discount_price = 0;

        if(!empty($data['list'])&&!empty($data['coupon_id'])){

            $record_model = new CouponRecord();

            $coupon_limit = new CouponLimit();

            $coupon       = $record_model->dataInfo(['id'=>$data['coupon_id']]);
            //该订单所有的商品id
            $goods_id     = array_column($data['list'],'goods_id');
            //可以被抵扣的商品的价格
            $goods_price  = 0;

            foreach ($data['list'] as &$v){

                $now_price = $v['true_price']*$v['num'];

                $dis = [

                    'is_record' => 1,

                    'type'      => $coupon['limit_type'],

                    'uniacid'   => $coupon['uniacid'],

                    'coupon_id' => $coupon['id']
                ];

                $obj_id = $coupon_limit->where($dis)->column('obj_id');
                //检测是否在该分类中
                if($coupon['limit_type']==1&&!in_array($v['cate_id'],$obj_id)){

                    $key = array_search($v['goods_id'],$goods_id);

                    unset($goods_id[$key]);

                    $now_price = 0;

                }
                //检测是否在该商品中
                if($coupon['limit_type']==2){

                    $goods_model = new Goods();

                    $obj_id  = $goods_model->where('top_id','in',$obj_id)->column('id');

                    if(!in_array($v['goods_id'],$obj_id)){

                        $now_price    = 0;

                        $key = array_search($v['goods_id'],$goods_id);

                        unset($goods_id[$key]);
                    }
                }

                $goods_price+=$now_price;
            }
            //抵扣的钱
            $discount_price = $coupon['discount']>$goods_price?$goods_price:$coupon['discount'];

            $bin = $goods_price>0?1 - $discount_price/$goods_price:1;

            foreach ($data['list'] as &$value){

                if(in_array($value['goods_id'],$goods_id)){
                    //抵扣券后每个商品的价格
                    $value['true_price']    = round($value['true_price']*$bin,2);

                    $value['feeding_price'] = round($value['feeding_price']*$bin,2);

                }

            }

        }

        $data['discount_price'] = round($discount_price,2);

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:获取下单列表页的信息
     *
     * type：1 外卖 2：堂食
     */
    public function carListOrder($store_id,$type,$user_id,$uniacid,$coupon_id=0,$address_id=0,$user_num = 0){
        //获取购物车信息
        $data = $this->getCarList($user_id,$type,$uniacid,$store_id);

        $coupon_record = new CouponRecord();

        $o_data = $this->getCarPrice($data,$user_id,$uniacid,$type);
        //计算价格 外卖要计算配送费
        $data = $this->getCarPrice($data,$user_id,$uniacid,$type,$coupon_id,$address_id,$store_id,$user_num);
        //可用优惠券
        $data['coupon_list'] = $coupon_record->canUseCoupon($o_data,$user_id,$uniacid,$type,$store_id);

        return $data;
    }











}